package com.example.demo.command;

import jakarta.annotation.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.jdbc.support.rowset.SqlRowSetMetaData;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.table.ArrayTableModel;
import org.springframework.shell.table.BorderStyle;
import org.springframework.shell.table.Table;
import org.springframework.shell.table.TableBuilder;
import org.springframework.shell.table.TableModel;

@ShellComponent
public class DatebaseCommand {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @ShellMethod(key = "select")
    public Table select(String tableName, String columns) {
        SqlRowSet sqlRowSet = jdbcTemplate.queryForRowSet("select * from manage_route");
        SqlRowSetMetaData metaData = sqlRowSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        String[][] data = {};
        // 获取列名列表
        String[] columnNames = new String[columnCount];
        for (int i = 0; i < columnCount; i++) {
            columnNames[i] = metaData.getColumnName(i + 1);
            data[0] = columnNames;
        }
        while (sqlRowSet.next()) {
            String[] rowDatas = new String[columnCount];
            for (int i = 0; i < columnCount; i++) {
                Object object = sqlRowSet.getObject(i + 1);
                rowDatas[i] = String.valueOf(object);
                data[data.length] = rowDatas;
            }
        }
        return createTable(data);
    }

    private Table createTable(String[][] data) {
        TableModel model = new ArrayTableModel(data);
        TableBuilder tableBuilder = new TableBuilder(model);

        // 添加边框样式
        tableBuilder.addFullBorder(BorderStyle.fancy_light);

        return tableBuilder.build();
    }


    @ShellMethod(key = "reset-password")
    public String resetPassword(String username, String password) {
        jdbcTemplate.update("UPDATE manage_account SET password = ? WHERE username = ?", password, username);
        return "OK";
    }



}
